package com.x.erp.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.x.erp.payload.SmsCodeMsg;
import com.x.erp.util.ConstantTopic;
import com.x.framework.redis.XRedisTemplate;
import com.x.rocketmq.RocketMqProducer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.config.annotation.Reference;
import com.x.erp.json.ErpMobileUser;
import com.x.erp.model.User;
import com.x.erp.rpc.UserRpcService;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import com.x.security.model.Account;
import com.x.security.model.SecurityAccount;
import com.x.security.rpc.SecurityRpcService;
import com.x.security.util.Constant;

@RestController
public class UserController extends BaseController {
	private static ModelAndView loginModelAndView = new ModelAndView(Constant.redirect + "/home/index.jsp");
	private static ModelAndView exceptionModelAndView = new ModelAndView("/common/exception.jsp");

	@Reference
	private UserRpcService userRpcService;

	@Reference
	private SecurityRpcService securityRpcService;

	@Autowired
	private RocketMqProducer rocketMqProducer;

	@Autowired
	private XRedisTemplate redis;


	@RequestMapping("/getUserSession")
	public ModelAndView login(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object obj = session.getAttribute(Constant.SECURITY_ACCOUNT);
		if (obj != null) {
			SecurityAccount securityAccount = (SecurityAccount) obj;
			String accountId = securityAccount.getAccountId();
			User user = new User();
			user.setAccountId(accountId);
			List<User> userList = userRpcService.selectUserList(user);
			if (userList.size() > 0) {
				user = userList.get(0);
				session.setAttribute("userId", user.getUserId());
				session.setAttribute("userName", user.getUserName());
				session.setAttribute("userMobile", user.getUserMobile());
				session.setAttribute("userType", user.getUserType());
				session.setAttribute("userState", user.getUserState());
				if (StringUtils.isNotEmpty(user.getMarketId())) {
					session.setAttribute("marketId", user.getMarketId());
				} else {
					request.setAttribute(Constant.MESSAGE, "市场ID为空");
					return exceptionModelAndView;
				}
				if (StringUtils.isNotEmpty(user.getShopId())) {
					session.setAttribute("shopId", user.getShopId());
				}
				return loginModelAndView;
			} else {
				request.setAttribute(Constant.MESSAGE, "不存在该用户信息");
				return exceptionModelAndView;
			}
		} else {
			request.setAttribute(Constant.MESSAGE, "用户信息过期");
			return exceptionModelAndView;
		}
	}

	@RequestMapping(value = "/LoginJson", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel loginJson(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Object obj = session.getAttribute(Constant.SECURITY_ACCOUNT);
		if (obj == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, Constant.securityAccountErrorMessage);
		}
		SecurityAccount securityAccount = (SecurityAccount) obj;

		User user = new User();
		user.setAccountId(securityAccount.getAccountId());
		List<User> userList = userRpcService.selectUserList(user);
		if (userList.size() == 0) {
			return new ResultModel(ResultCode.RESULT_FAIL, Constant.securityAccountErrorMessage);
		} else {
			user = userList.get(0);
		}

		if(StringUtils.isEmpty(user.getWxOpenId())){
			String wxOpenId = securityAccount.getWxOpenId();
			User wxUser = new User();
			wxUser.setUserId(user.getUserId());
			wxUser.setWxOpenId(wxOpenId);
			userRpcService.updateUser(wxUser);
			Account account = new Account();
			account.setAccountId(user.getAccountId());
			account.setAccountModifyTime(new Date());
			Map<String, String> accountPropertyMap = new HashMap<String, String>();
			accountPropertyMap.put("wxOpenId", wxOpenId);
			account.setAccountPropertyMap(accountPropertyMap);
			securityRpcService.updateAccount(account);
		}

		ErpMobileUser erpMobileUser = new ErpMobileUser();
		erpMobileUser.setAccountId(securityAccount.getAccountId());
		erpMobileUser.setAccountName(securityAccount.getAccountName());
		erpMobileUser.setAccountRemark(securityAccount.getAccountRemark());
		erpMobileUser.setAccountPropertyMap(securityAccount.getAccountPropertyMap());
		erpMobileUser.setResourceList(securityAccount.getResourceList());
		erpMobileUser.setRoleList(securityAccount.getRoleList());
		erpMobileUser.setApplicationId(securityAccount.getApplicationId());

		erpMobileUser.setUserId(user.getUserId());
		erpMobileUser.setUserName(user.getUserName());
		erpMobileUser.setUserMobile(user.getUserMobile());

		erpMobileUser.setMarketId(user.getMarketId());
		if (user.getMarket() != null) {
			erpMobileUser.setMarketName(user.getMarket().getMarketName());
			erpMobileUser.setMarketLogo(user.getMarket().getMarketLogo());
		}

		erpMobileUser.setShopId(user.getShopId());
		if (user.getShop() != null) {
			erpMobileUser.setShopName(user.getShop().getShopName());
		}

		session.removeAttribute(Constant.SECURITY_ACCOUNT);
		return new ResultModel(ResultCode.RESULT_SUCCESS, null, erpMobileUser);
	}


	/**
	 * 通过wxOpenId登录
	 * @param securityAccount
	 * @return
	 */
	@RequestMapping(value = "/LoginWxOpenId", method = {RequestMethod.POST, RequestMethod.GET})
	public ModelAndView loginWxOpenId(SecurityAccount securityAccount) {
		String wxOpenId = securityAccount.getWxOpenId();
		if(StringUtils.isEmpty(wxOpenId)){
			return new ModelAndView("/controller/LoginJson");
		}
		String applicationId = securityAccount.getApplicationId();
		applicationId = StringUtils.isEmpty(applicationId) ? Constant.applicationId : applicationId;

		User user = new User();
		user.setWxOpenId(wxOpenId);
		List<User> userList = userRpcService.selectUserList(user);
		if (userList.size() == 0) {
			return new ModelAndView("/controller/LoginJson");
		} else {
			user = userList.get(0);
			String accountId = user.getAccountId();
			return new ModelAndView(Constant.redirect + "/controller/Login?loginUrl=/controller/LoginJson&logoutUrl=/controller/LoginJson&exceptionUrl=/controller/LoginJson&accountId=" + accountId + "&applicationId=" + applicationId);
		}
	}

	/**
	 * 解除用户微信OpenId绑定
	 * @param request
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/unbindUserWxOpenId", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel unbindWxOpenId(HttpServletRequest request, String userId) {
		if(StringUtils.isEmpty(userId)){
			return new ResultModel(ResultCode.RESULT_FAIL, "用户ID不能为空！");
		}
		User user = new User();
		user.setUserId(userId);
		user.setWxOpenId("null");
		userRpcService.updateUser(user);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "解除绑定成功！");
	}

	/**
	 * 修改密码
	 *
	 * @return
	 */
	@RequestMapping(value = "/updatePwd", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel updatePwd(String accountName, String accountPassword, String newPassword) {
		if (StringUtils.isEmpty(accountName)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户名不能为空！");
		}
		if (StringUtils.isEmpty(accountPassword)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "密码不能为空！");
		}
		if (StringUtils.isEmpty(newPassword)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "新密码不能为空！");
		}
		Account account = new Account();
		account.setAccountName(accountName);
		//查询帐户信息
		List<Account> accounts = securityRpcService.selectAccountList(account);
		if (accounts != null && accounts.size() == 1) {
			account = accounts.get(0);
			if (!securityRpcService.validateAccountPassword(accountPassword, account.getAccountPassword())) {
				return new ResultModel(ResultCode.RESULT_FAIL, "密码错误！");
			}
			//新密码信息
			Account newAccount = new Account();
			newAccount.setAccountId(account.getAccountId());//帐户ID
			newAccount.setAccountPassword(newPassword);//新密码
			securityRpcService.updateAccount(newAccount);//修改帐户信息
			return new ResultModel(ResultCode.RESULT_SUCCESS, "修改密码成功！");
		}
		return new ResultModel(ResultCode.RESULT_FAIL, "用户名密码错误！");
	}


	/**
	 * 获取短信验证码
	 * @return
	 */
	@RequestMapping(value = "/getSmsValidateCode", method =  {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getSmsValidateCode(String userMobile){
		if(StringUtils.isEmpty(userMobile)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户手机号不能为空！");
		}
		User user = new User();
		user.setUserMobile(userMobile);
		int userNum = userRpcService.selectUserNum(user);
		if (userNum > 0){
			try {
				SmsCodeMsg smsCodeMsg = new SmsCodeMsg();
				smsCodeMsg.setUserMiobile(userMobile);
				Random r = new Random();
				String validateCode = String.format("%06d", r.nextInt(1000000));
				smsCodeMsg.setValidateCode(validateCode);
				redis.set("smsValidateCode_" + userMobile, smsCodeMsg, 5 * 60);
				rocketMqProducer.produceMessage(ConstantTopic.TOPIC_ERP_CAR, ConstantTopic.TAG_FIND_BACK_PASSWORD, smsCodeMsg);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("获取短信验证码异常", e);
			}
		}else{
			return new ResultModel(ResultCode.RESULT_FAIL, "请输入正确账户信息！");
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "短信已发送，请查看");
	}



	/**
	 * 找回密码
	 *
	 * @return
	 */
	@RequestMapping(value = "/findPwd", method =  {RequestMethod.POST, RequestMethod.GET})
	public ResultModel findPwd(String validateCode , String userMobile, String newPassword){
		if (StringUtils.isEmpty(validateCode)){
			return new ResultModel(ResultCode.RESULT_FAIL, "验证码不能为空！");
		}
		if (StringUtils.isEmpty(userMobile) || userMobile.length() != 11){
			return new ResultModel(ResultCode.RESULT_FAIL, "请输入有效的手机号！");
		}
		if (StringUtils.isEmpty(newPassword) || newPassword.length() < 6 || newPassword.length() > 16){
			return new ResultModel(ResultCode.RESULT_FAIL, "请输入有效的密码(6到16位)！");
		}
		SmsCodeMsg smsCodeMsg = JSON.parseObject(redis.get("smsValidateCode_" + userMobile), SmsCodeMsg.class);
		if(smsCodeMsg == null || !smsCodeMsg.getValidateCode().equals(validateCode)){
			return new ResultModel(ResultCode.RESULT_FAIL, "验证码不正确");
		}
		User user = new User();
		user.setUserMobile(userMobile);
		List<User> userList = userRpcService.selectUserList(user);
		if (userList != null && userList.size() > 0){
			Account account = new Account();
			account.setAccountId(userList.get(0).getAccountId());
			account.setAccountPassword(newPassword);
			securityRpcService.updateAccount(account);
		}else{
			return new ResultModel(ResultCode.RESULT_FAIL, "不存在此账户信息");
		}
		redis.delete("smsValidateCode_" + userMobile);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "密码重置成功");
	}




	/**
	 * 查询用户列表
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getUserList", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getUserList(User user) {
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功！", userRpcService.selectUserList(user));
	}

	/**
	 * PC查询不包含车商车商员工用户列表
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getMarketUserList", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getMarketUserList(User user) {
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功！", userRpcService.selectMarketUserList(user));
	}

	/**
	 * PC查询不包含车商车商员工用户数量
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getMarketUserNum", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getMarketUserNum(User user) {
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功！", userRpcService.selectMarketUserNum(user));
	}



	/**
	 * 查询用户数量
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getUserNum", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getUserNum(User user) {
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功！", userRpcService.selectUserNum(user));
	}

	/**
	 * 根据ID查询用户信息
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getUserById", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel getUserById(User user) {
		if (user == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户信息不能为空");
		}
		if (StringUtils.isEmpty(user.getUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户ID不能为空");
		}
		User userInfo = userRpcService.selectUserInfoById(user);
		if (userInfo == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户ID错误");
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功！", userInfo);
	}

	/**
	 * 新用户
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/insertUser", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel insertUser(User user) {
		if (user == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户信息不能为空");
		}
		if (user.getUserType() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户类型不能为空");
		}
		if (StringUtils.isEmpty(user.getUserName())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户姓名不能为空");
		}
		if (StringUtils.isEmpty(user.getUserMobile())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户联系方式不能为空");
		}
		if (StringUtils.isEmpty(user.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空");
		}
		User valiUser = new User();
		valiUser.setUserMobile(user.getUserMobile());
		List<User> list = userRpcService.selectUserList(valiUser);
		if(list != null && list.size() > 0){
			return new ResultModel(ResultCode.RESULT_FAIL, "手机号已存在，请直接登录或更换手机号注册！");
		}
		Date cDate = new Date();
		user.setUserState(1);
		user.setUserCreateTime(cDate);
		user.setUserUpdateTime(cDate);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "新增成功！", userRpcService.insertUser(user));
	}

	/**
	 * 修改用户信息
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/updateUser", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel updateUser(User user) {
		if (user == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户信息不能为空");
		}
		if (StringUtils.isEmpty(user.getUserId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户ID不能为空");
		}
		if(StringUtils.isNotEmpty(user.getUserMobile())) {
			User valiUser = new User();
			valiUser.setUserMobile(user.getUserMobile());
			List<User> users = userRpcService.selectUserList(valiUser);
			if (users != null && users.size() > 0) {
				//如果用户根据手机号查询出来的id和参数不匹配，为不同用户
				if (!users.get(0).getUserId().equals(user.getUserId())) {
					return new ResultModel(ResultCode.RESULT_FAIL, "手机号已存在，请直接登录或更换手机号！");
				}
			}
		}
		user.setUserUpdateTime(new Date());
		userRpcService.updateUser(user);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "修改成功！");
	}

	/**
	 * 验证用户是否存在
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/selectUserByMobile", method = {RequestMethod.POST, RequestMethod.GET})
	public ResultModel selectUserByMobile(User user) {
		if (user == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户信息不能为空");
		}
		if (StringUtils.isEmpty(user.getUserMobile())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "用户手机号不能为空");
		}
		String userId = user.getUserId();
		user.setUserId(null);
		List<User> list = userRpcService.selectUserList(user);
		Account  account = new Account();
		account.setAccountName(user.getUserMobile());
		List<Account>  listAcccount = securityRpcService.selectAccountList(account);
		User userInfo = null;
		if (list!=null && list.size() > 0){
			userInfo = list.get(0);
		}
		Account  accountInfo = null;
		if (listAcccount !=null && listAcccount.size() > 0){
			accountInfo = listAcccount.get(0);
		}
	    if (StringUtils.isEmpty(userId)){
			if (userInfo!= null || accountInfo !=null ){
				return new ResultModel(ResultCode.RESULT_FAIL, "用户手机号已注册，请更换手机号！");
			}
	    }else{
		    if (userInfo == null || accountInfo == null || !(userInfo.getUserId().equals(userId) && userInfo.getAccountId().equals(accountInfo.getAccountId()))){
			    return new ResultModel(ResultCode.RESULT_FAIL, "用户手机号已注册，请更换手机号！");
		    }
	    }
//		if (list != null && list.size() > 0  && (StringUtils.isEmpty(userId) || !list.get(0).getUserId().equals(userId))){
//			return new ResultModel(ResultCode.RESULT_FAIL, "用户手机号已注册，请更换手机号！");
//		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "验证通过！");
	}


}